package com.ptt.sqm.session;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;

import org.ksoap2.serialization.PropertyInfo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ptt.sqm.activity.LoginActivity;
import com.ptt.sqm.model.AssessItemChoice5018;
import com.ptt.sqm.model.AssessSubject5019;
import com.ptt.sqm.model.AssessSuggestion5034;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.SuggestionImage;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.UploadCall;
import com.ptt.sqmonmobile.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

public class CacheManager {
	 private static final long MAX_SIZE = 1024 * 1024 * 50; // 50MB
	
	 private static final long CLEAR_SIZE = 1024 * 1024 * 50; // 5MB

	private static File cacheDir;

	private static final Type MAP_TYPE = new TypeToken<AssessTran>() {
	}.getType();

	private static final Type ORDER_TYPE = new TypeToken<LinkedHashSet<String>>() {
	}.getType();

	public static void cacheData(Context context) throws IOException {

		try {
			Context mContext = context.createPackageContext(context.getPackageName(), Context.CONTEXT_IGNORE_SECURITY);

			cacheDir = new File(mContext.getFilesDir().getParentFile().getAbsolutePath() + "/shared_prefs");

			long size = getDirSize(cacheDir);
			if (size > MAX_SIZE) {
				cleanSaveAssessTran(context);
			}

		} catch (Exception e) {
		} finally {

		}
	}

	private static void cleanDir(File dir) {

		File[] files = dir.listFiles();

		for (File file : files) {

			file.delete();

		}
	}

	private static void cleanSaveAssessTran(Context context) {
		SharedPreferences tranPrefs = context.getSharedPreferences(AppUtil.SAVED_TRAN_ASSESS_PREF, Context.MODE_PRIVATE);
		SharedPreferences itemPrefs = context.getSharedPreferences(AppUtil.SAVED_ITEM_ASSESS_PREF, Context.MODE_PRIVATE);
		SharedPreferences summaryPrefs = context.getSharedPreferences(AppUtil.SAVED_SUMMARY_ASSESS_PREF, Context.MODE_PRIVATE);

		LinkedHashSet<String> order = new Gson().fromJson(tranPrefs.getString(AppUtil.SAVED_TRAN_ASSESS_ORDER, null), ORDER_TYPE);
		List<String> tempOrder = new ArrayList<String>();
		if (order != null) {
			SharedPreferences.Editor tranEditor = tranPrefs.edit();
			SharedPreferences.Editor itemEditor = itemPrefs.edit();
			SharedPreferences.Editor summaryEditor = summaryPrefs.edit();
			for (String key : (String[]) order.toArray(new String[order.size()])) {

				deleteImageOnTemp(context, (AssessTran) new Gson().fromJson(tranPrefs.getString(key, null), MAP_TYPE));

				tranEditor.remove(key);
				tranEditor.commit();

				itemEditor.remove(key);
				itemEditor.commit();

				summaryEditor.remove(key);
				summaryEditor.commit();

				tempOrder.add(key);

				long size = getDirSize(cacheDir);

				Log.i("DIR_SIZE", String.valueOf(size));
				Log.i(AppUtil.SAVED_TRAN_ASSESS_ORDER, key);

				if (size < MAX_SIZE - CLEAR_SIZE) {
					break;
				}
			}

			for (String temp : tempOrder) {
				order.remove(temp);
			}

			tranEditor.putString(AppUtil.SAVED_TRAN_ASSESS_ORDER, new Gson().toJson(order));
			tranEditor.commit();
		}

	}

	private static long getDirSize(File dir) {

		long size = 0;
		File[] files = dir.listFiles();

		for (File file : files) {
			if (file.isFile()) {
				size += file.length();
			}
		}

		return size;
	}

	private static void deleteImageOnTemp(Context context, AssessTran saveAssessTran) {
		// TODO Auto-generated method stub

		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019Map.values()) {

			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoiceMap.values()) {

				if (item.AssessChoicePoint.length() != 0)

					if (item.Suggestions != null && item.Suggestions.size() != 0) {
						for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034Map.values()) {
							if (suggestion.Images != null) {
								for (SuggestionImage image : suggestion.Images.get(0).SuggestionImage) {

									WidgetUtil.deleteImageOnDevice(context,
										new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.image_path) + AppUtil.PATH
											+ image.FILE_SAVE_NAME));

								}
							}
						}
					}
			}
		}

	}

}
